package com.attack.manager;

import java.math.BigDecimal;

import org.springframework.stereotype.Service;

import com.attack.model.OrderDetailModel;
import com.attack.model.OrderInfoModel;
import com.common.manager.BaseManager;
import com.common.utils.DateUtil;

@Service(value = "orderDetailManager")
public class OrderDetailManager  extends BaseManager{
	
	static int baseMoney=200000;//20万
	
	@Override
	public void setSqlMapNameSpace() {
		this.sqlMapNameSpace = "com.attack.manager.model.orderDetailModel";
	}
    
	/**
	 *  功能：插入订单明细
	 * @param orderId 订单ID
	 * @param startDate 计息开始日
	 * @param orderMonth 投资期限
	 * @param totalIncome 总收益
	 * @param totalfinance 本金
	 */
	public void updateOrderDetail(OrderInfoModel orderInfoModel){
		int orderId = orderInfoModel.getIntID();
		String startDate = orderInfoModel.getInterestStartDate();
		int orderMonth = orderInfoModel.getPeriodDay();
		BigDecimal totalIncome = new BigDecimal(orderInfoModel.getTotalMoney());
		BigDecimal totalfinance =  new BigDecimal(orderInfoModel.getRealIncome());
		
		OrderDetailModel conditionObj = new OrderDetailModel();
		conditionObj.setOrderId(orderId);
		super.deleteObject(conditionObj);
		
		OrderDetailModel orderDetailModel = new OrderDetailModel();
		BigDecimal income = new BigDecimal(0);
		BigDecimal subTotalNum = new BigDecimal(0);
		OrderDetailModel tempOrder = null;
		for(int i=1;i<orderMonth;i++){
			orderDetailModel.setOrderId(orderId);
			orderDetailModel.setOrderMonth(DateUtil.getMonthOfDate(startDate,i));
			 tempOrder = (OrderDetailModel)super.getObjectInfo("getObjectInfoById", orderDetailModel);
			if(tempOrder!=null){
				if(("1".equals(tempOrder.getStatus()))){
					subTotalNum = subTotalNum.add(tempOrder.getMonthIncome());
				}else{
					income= totalIncome.divide(new BigDecimal(orderMonth),0,BigDecimal.ROUND_HALF_UP);
					subTotalNum = subTotalNum.add(income);
					orderDetailModel.setMonthIncome(income);
					orderDetailModel.setStatus("0");
					super.updateObject(orderDetailModel);
				}
			}else{
				income= totalIncome.divide(new BigDecimal(orderMonth),0,BigDecimal.ROUND_HALF_UP);
				subTotalNum = subTotalNum.add(income);
				orderDetailModel.setMonthIncome(income);
				orderDetailModel.setStatus("0");
				super.insertObject(orderDetailModel);
			}
		}
		
		//最后一个月的订单，是本金+收益一起
		orderDetailModel.setOrderId(orderId);
		orderDetailModel.setOrderMonth(DateUtil.getMonthOfDate(startDate,orderMonth,-1));
		orderDetailModel.setMonthIncome(totalfinance.add(totalIncome.subtract(subTotalNum)));//最后一个月本金+利息
		orderDetailModel.setStatus("0");
		 tempOrder = (OrderDetailModel)super.getObjectInfo("getObjectInfoById", orderDetailModel);
			if(tempOrder!=null){
				if(("0".equals(tempOrder.getStatus()))){
					super.updateObject(orderDetailModel);
				}
			}else{
				super.insertObject(orderDetailModel);
			}
	}
    
}
